package leetcode;

public class Leetcode25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode tail = dummy;

        while(tail.next!=null){
            //检查是否够k个翻转
            for (int i = 0; i < k && tail!=null; i++) {
                tail = tail.next;

            }
            if(tail==null){
                break;//不够就直接退出
            }
            //翻转前的准备
            //储存下一段链表的位置
            //并且断开链表
            //翻转链表
            //连接链表
            ListNode next = tail.next;
            tail.next = null;
            ListNode start = pre.next;
            pre.next = reverse(start);
            start.next = next;
            pre = start;
            tail = pre;
        }
        return dummy.next;
    }

    public ListNode reverse(ListNode head){
        ListNode dummy = null;
        ListNode cur = head;
        while(cur!=null){
            ListNode tmp = cur.next;
            cur.next = dummy;
            dummy = cur;
            cur = tmp;
        }
        return dummy;
    }
}
